<?php

// Namespace

namespace Loop;


/**
 * CModelManager allows to manage models
 */

class CModelManager
{
	/**
	 * Gets models (recursive function)
	 *
	 * @param	string	$namespace 	The namespace the models belong to.
	 * @param	string	$path		The path in which models are stored. If none, will search in all extensions + app
	 *
	 * @return	array	The array which contains the list of models per extension (className => pathToModel)
	 */
	
	public function getModels($namespace, $path = null)
	{
		// We'll store models here
		
		$models = array();
				

		// Look for models in this path
		
		$pathToFiles = app()->getFileHelper()->listFiles($path, 'C*.php');
		

		// Parse the list of files
		
		foreach ($pathToFiles as $pathToFile)
		{
			// Use the model only if it's NOT abstract
			
			require_once($pathToFile);
			
			$fragments = explode('/', $pathToFile);
			$lastFragment = array_pop($fragments);
			$fragments = explode('.php', $lastFragment);
			$className =  array_shift($fragments);


			$namespaceClassName = $namespace . '\\' .$className;

			// Does the class exist?

			if (class_exists($namespaceClassName) === false)
			{
				
				if (class_exists($className) == false)
				{
					continue;
				}

				$reflection = new \ReflectionClass($className);
			}
			else
			{
				// Is it abstract?
				
				$reflection = new \ReflectionClass($namespaceClassName);
			}

			// Is it abstract?
			
			if 
			(
				$reflection->isAbstract() == true || 
				$reflection->isAbstract() == true
			)
			{
				continue;
			}
			
			
			// Add this model to the list we will return
			
			$models[] = $className;
		}

		return $models;
	}
}

?>
